// pages/goods_detail/index.js
const {
  collectionDelete,
  collectionInsert,
  cartDelete,
  cartInsert
}=require("../../utils/insertAndDelete");//导入文件中的函数
Page({
  data: {
    goodsDetail: {},
    // 商品是否被收藏过
    isCollect: false,
    optionsID:""
  },
  onLoad: function (options) {
    wx.request({
      url: 'http://122.112.245.197:5000/api/details?id=' + options.id,
      success:(res=>{
        //console.log(res);
         this.setData({
          goodsDetail:res.data,
          optionsID:options.id
        }) 
        console.log(options.id)
      })
    })
  },

  // 点击轮播图放大预览
  handlePrevewImage(e) {
    const urls = this.GoodsDetail.pics.map(v => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    });
  },
  // 点击加入购物车
  handleCartAdd() {
    var data={
      userID:wx.getStorageSync('iphone'),
      name:this.data.goodsDetail.goods_name,
      num:1,
      price:this.data.goodsDetail.goods_price,
      pic:this.data.goodsDetail.goods_big_logo,
      pID:this.data.optionsID,
      choose:"X"
    }
    cartInsert({
      data,
      success:(res)=>{
        wx.showModal({
          cancelColor: 'cancelColor',
          title:"加入购物车",
          content:"成功加入购物车！"
        })
      }
    })
    // 判断商品对象是否存入在购物车中
    
      // 不存在 第一次加入
      
      // 已存在 数量++
  },

  // 点击商品收藏
  handleCollect() {
    if(this.data.isCollect==false){
      
      var data={
        userID:wx.getStorageSync('iphone'),
        name:this.data.goodsDetail.goods_name,
        num:1,
        price:this.data.goodsDetail.goods_price,
        pic:this.data.goodsDetail.goods_big_logo,
        pID:this.data.goodsDetail._id
      }
      collectionInsert({
        data,
        success:(res)=>{
          wx.showToast({
          title: '收藏',
         content:"收藏成功！"
          })
        }
      })
      this.setData({
        isCollect:true
      })
    }
    else{
      var data={
        userID:wx.getStorageSync('iphone'),
        name:this.data.goodsDetail.goods_name,
        num:1,
        price:this.data.goodsDetail.goods_price,
        pic:this.data.goodsDetail.goods_big_logo,
        pID:this.data.goodsDetail._id
      }
      collectionDelete({
        data,
        success:(res)=>{
          wx.showToast({
          title: '取消收藏',
          content:"取消成功！"
        })
        }
      })
      
      this.setData({
        isCollect:false
      })
    }
  }
})